package com.unis.service.fzzx.impl;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.unis.common.secure.authc.UserInfo;
import com.unis.common.util.GeneratFileUtil;
import com.unis.common.util.StrUtil;
import com.unis.common.util.TemplateUtil;
import com.unis.common.util.TimeUtil;
import com.unis.dto.ResultDto;
import com.unis.model.fzzx.Jjd;
import com.unis.model.fzzx.JjdShr;
import com.unis.model.system.Jgz;
import com.unis.model.znzf.Jlt;
import com.unis.pojo.Attachment;
import com.unis.service.fzzx.JjdService;
import com.unis.service.fzzx.JjdShrService;
import com.unis.service.gab.GabDxzpAjxxService;
import com.unis.service.system.AttachmentService;
import com.unis.service.system.CodeService;
import com.unis.service.system.JgzService;
import com.unis.service.znzf.JltService;
import com.unis.service.znzf.SfMxJgLstService;
import com.unis.service.znzf.YhkMxJgLstService;
import org.apache.commons.lang.math.NumberUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.apache.commons.lang.StringUtils;
import tk.mybatis.mapper.entity.Example;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.PageHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.unis.service.impl.BaseServiceImpl;
import com.unis.mapper.fzzx.JjdYpbgMapper;
import com.unis.model.fzzx.JjdYpbg;
import com.unis.service.fzzx.JjdYpbgService;
import com.unis.common.exception.app.AppRuntimeException;

/**
 * <pre>
 * @see JjdYpbgService
 * </pre>
 *
 * @author xuk
 * @version 1.0
 * @since 2019-08-16
 */
@Service("jjdYpbgService")
public class JjdYpbgServiceImpl extends BaseServiceImpl implements JjdYpbgService {
	private static final Logger logger = LoggerFactory.getLogger(JjdYpbgServiceImpl.class);
    @Autowired
    private JjdYpbgMapper jjdYpbgMapper;

	@Autowired
	private JjdService jjdService;
	@Autowired
	private JgzService jgzService;
	@Autowired
	private JjdShrService jjdShrService;
	@Autowired
	private YhkMxJgLstService yhkMxJgLstService;
	@Autowired
	private SfMxJgLstService sfMxJgLstService;
	@Autowired
	private JltService jltService;
	@Autowired
	private GabDxzpAjxxService gabDxzpAjxxService;
	@Autowired
	private AttachmentService attachmentService;
	@Autowired
	private CodeService codeService;

    /**
     * @see JjdYpbgService#insert(JjdYpbg jjdYpbg)
     */
    @Override
    public int insert(JjdYpbg jjdYpbg) throws Exception {
    	if (jjdYpbg!=null){
	        jjdYpbg.setPk(TemplateUtil.genUUID());
			UserInfo userInfo = this.getUserInfo();
			jjdYpbg.setLrdwdm(userInfo.getJgdm());
	        jjdYpbg.setLrdwmc(userInfo.getJgmc());
	        jjdYpbg.setLrrjh(userInfo.getJh());
	        jjdYpbg.setLrrxm(userInfo.getXm());
	        return jjdYpbgMapper.insertSelective(jjdYpbg);
    	}else{
    		logger.error("JjdYpbgServiceImpl.insert时jjdYpbg数据为空。");
    		throw new AppRuntimeException("JjdYpbgServiceImpl.insert时jjdYpbg数据为空。");
    	}        
    }

    /**
     * @see JjdYpbgService#delete(String pk)
     */
    @Override
    public int delete(String pk) throws Exception {
    	if(StringUtils.isBlank(pk)){
    		logger.error("JjdYpbgServiceImpl.delete时pk为空。");
    		throw new AppRuntimeException("JjdYpbgServiceImpl.delete时pk为空。");
    	}else{
    		return jjdYpbgMapper.deleteByPrimaryKey(pk);
    	}
    }

    /**
     * @see JjdYpbgService#updateByPrimaryKey(JjdYpbg jjdYpbg)
     */
    @Override
    public int updateByPrimaryKey(JjdYpbg jjdYpbg) throws Exception {
        if (jjdYpbg!=null){
        	if(StringUtils.isBlank(jjdYpbg.getPk())){
        		logger.error("JjdYpbgServiceImpl.updateByPrimaryKey时jjdYpbg.Pk为空。");
        		throw new AppRuntimeException("JjdYpbgServiceImpl.updateByPrimaryKey时jjdYpbg.Pk为空。");
        	}
	        return jjdYpbgMapper.updateByPrimaryKeySelective(jjdYpbg);
    	}else{
    		logger.error("JjdYpbgServiceImpl.updateByPrimaryKey时jjdYpbg数据为空。");
    		throw new AppRuntimeException("JjdYpbgServiceImpl.updateByPrimaryKey时jjdYpbg数据为空。");
    	}
    }
    /**
     * @see JjdYpbgService#queryJjdYpbgByPrimaryKey(String pk)
     */
    @Override
    public JjdYpbg queryJjdYpbgByPrimaryKey(String pk) throws Exception {
    	if(StringUtils.isBlank(pk)){
    		logger.error("JjdYpbgServiceImpl.queryJjdYpbgByPrimaryKey时pk为空。");
    		throw new AppRuntimeException("JjdYpbgServiceImpl.queryJjdYpbgByPrimaryKey时pk为空。");
    	}else{
    		return jjdYpbgMapper.selectByPrimaryKey(pk);
    	}
    }
    

    /**
     * @see JjdYpbgService#queryAsObject(JjdYpbg jjdYpbg)
     */
    @Override
    public JjdYpbg queryAsObject(JjdYpbg jjdYpbg) throws Exception {
        if (jjdYpbg!=null){
	        return jjdYpbgMapper.selectOne(jjdYpbg);
    	}else{
    		logger.error("JjdYpbgServiceImpl.queryAsObject时jjdYpbg数据为空。");
    		throw new AppRuntimeException("JjdYpbgServiceImpl.queryAsObject时jjdYpbg数据为空。");
    	}
    }

    /**
     * @see JjdYpbgService#queryCountByExample(Example example)
     */
    @Override
    public int queryCountByExample(Example example) throws Exception {
    	if(example!=null){
    		return jjdYpbgMapper.selectCountByExample(example);
    	}else{
    		logger.error("JjdYpbgServiceImpl.queryCountByExample时example数据为空。");
    		throw new AppRuntimeException("JjdYpbgServiceImpl.queryCountByExample时example数据为空。");
    	}
    }
    /**
     * @see JjdYpbgService#queryListByExample(Example example)
     */
    @Override
    public List<JjdYpbg> queryListByExample(Example example) throws Exception {
    	if(example!=null){
    		return jjdYpbgMapper.selectByExample(example);
    	}else{
    		logger.error("JjdYpbgServiceImpl.queryListByExample时example数据为空。");
    		throw new AppRuntimeException("JjdYpbgServiceImpl.queryListByExample时example数据为空。");
    	}
    }
    /**
     * @see JjdYpbgService#queryPageInfoByExample(Example example,int pageNum,int pageSize)
     */
    @Override
    public PageInfo queryPageInfoByExample(Example example,int pageNum,int pageSize) throws Exception {    	
    	if(example!=null){
    		PageHelper.startPage(pageNum,pageSize);
    		return new PageInfo(jjdYpbgMapper.selectByExample(example));
    	}else{
    		logger.error("JjdYpbgServiceImpl.queryListByExample时example数据为空。");
    		throw new AppRuntimeException("JjdYpbgServiceImpl.queryListByExample时example数据为空。");
    	}    	
    }
	/**
     * @see JjdYpbgService#queryListByPage(Map parmMap,int pageNum,int pageSize)
     */
    @Override
    public ResultDto queryListByPage(Map parmMap, int pageNum, int pageSize) throws  Exception{
    	if (parmMap!=null){
    		Example example = new Example(JjdYpbg.class);
    		//example.setOrderByClause("rksj DESC,pk asc");设置排序
    		Example.Criteria criteria = example.createCriteria();

    		criteria.andEqualTo("yxx","1");//设置yxx=1
    		/**
    		 *此方法请根据需要修改下方条件
    		*/
    		//此查询仅针对单表查询，若需要多表查询，尽量使用配置Mapper.xml 和Mapper.java的方式
    		//生成条件中均为 and field = value 
    		//生成代码中，若表结构中有_等字符，生成字段可能会与实体类不同，请注意修改
    		
    		boolean flag = false;
    		if(parmMap.get("pk")!=null && StringUtils.isNotBlank(parmMap.get("pk").toString())){
				criteria.andEqualTo("pk",parmMap.get("pk").toString().trim());
				flag = true;
			}
    		if(parmMap.get("jjdpk")!=null && StringUtils.isNotBlank(parmMap.get("jjdpk").toString())){
				criteria.andEqualTo("jjdpk",parmMap.get("jjdpk").toString().trim());
				flag = true;
			}
    		if(parmMap.get("mongopk")!=null && StringUtils.isNotBlank(parmMap.get("mongopk").toString())){
				criteria.andEqualTo("mongopk",parmMap.get("mongopk").toString().trim());
				flag = true;
			}
    		if(parmMap.get("filename")!=null && StringUtils.isNotBlank(parmMap.get("filename").toString())){
				criteria.andEqualTo("filename",parmMap.get("filename").toString().trim());
				flag = true;
			}
    		if(parmMap.get("filetype")!=null && StringUtils.isNotBlank(parmMap.get("filetype").toString())){
				criteria.andEqualTo("filetype",parmMap.get("filetype").toString().trim());
				flag = true;
			}
    		if(parmMap.get("lrdwdm")!=null && StringUtils.isNotBlank(parmMap.get("lrdwdm").toString())){
				criteria.andEqualTo("lrdwdm",parmMap.get("lrdwdm").toString().trim());
				flag = true;
			}
    		if(parmMap.get("lrdwmc")!=null && StringUtils.isNotBlank(parmMap.get("lrdwmc").toString())){
				criteria.andEqualTo("lrdwmc",parmMap.get("lrdwmc").toString().trim());
				flag = true;
			}
    		if(parmMap.get("lrrxm")!=null && StringUtils.isNotBlank(parmMap.get("lrrxm").toString())){
				criteria.andEqualTo("lrrxm",parmMap.get("lrrxm").toString().trim());
				flag = true;
			}
    		if(parmMap.get("lrrjh")!=null && StringUtils.isNotBlank(parmMap.get("lrrjh").toString())){
				criteria.andEqualTo("lrrjh",parmMap.get("lrrjh").toString().trim());
				flag = true;
			}
    		if(parmMap.get("yxx")!=null && StringUtils.isNotBlank(parmMap.get("yxx").toString())){
				criteria.andEqualTo("yxx",parmMap.get("yxx").toString().trim());
				flag = true;
			}
    		if(parmMap.get("rksj")!=null && StringUtils.isNotBlank(parmMap.get("rksj").toString())){
				criteria.andEqualTo("rksj",parmMap.get("rksj").toString().trim());
				flag = true;
			}
    		//一个条件都没有的时候给一个默认条件
    		if(!flag){
    		
    		}
    		PageInfo pageInfo = this.queryPageInfoByExample(example,pageNum,pageSize);
			ResultDto result = new ResultDto();
			result.setRows(pageInfo.getList());
			result.setPage(pageInfo.getPageNum());
			//result.setTotal(pageInfo.getPages());
			result.setTotal((int)pageInfo.getTotal());
			return result;
    	}else{
			logger.error("JjdYpbgServiceImpl.queryListByPage时parmMap数据为空。");
			throw new AppRuntimeException("JjdYpbgServiceImpl.queryListByPage时parmMap数据为空。");
		}
    }


	@Override
	public int generatYpbg(String jjdpk) throws Exception {
		int flag = 0;
		Subject currentUser = SecurityUtils.getSubject();
		UserInfo info = (UserInfo) currentUser.getPrincipal();
		Example ypbgExample = new Example(JjdYpbg.class);
		ypbgExample.setOrderByClause("rksj desc");
		Example.Criteria ypbgCriteria = ypbgExample.createCriteria();
		ypbgCriteria.andEqualTo("jjdpk",jjdpk);
		List<JjdYpbg> ypbgList = this.queryListByExample(ypbgExample);
		if (ypbgList!=null && !ypbgList.isEmpty() && ypbgList.size()>0){
			if (ypbgList.size()>=3){
				if (!(currentUser.hasRole("_SYSTEMADMIN") || currentUser.hasRole("ADMIN"))){
					throw new AppRuntimeException("生成研判报告已超出最大数量。");
				}
			}
			JjdYpbg ypbg =  ypbgList.get(0);
			Date date = ypbg==null?null : ypbg.getRksj();
			if (date!=null && TimeUtil.addDay(date,1).getTime()>new Date().getTime()){
				throw new AppRuntimeException("近期已生成研判报告，如有必须再次生成的情况，请在24小时后再次生成。");
			}
		}
		//获取接警单
		Jjd jjd = jjdService.queryJjdByPrimaryKey(jjdpk);
		if (jjd==null){
			throw new AppRuntimeException("接警单不存在。");
		}
		//获取警官证配置
		Jgz jgz = jgzService.queryJgzByUserPkAndDwdm(info.getPk(),info.getJgdm());
		//获取金流图
		Example jltExample = new Example(Jlt.class);
		Example.Criteria jltCriteria = jltExample.createCriteria();
		jltCriteria.andEqualTo("jjdpk",jjdpk);
		jltCriteria.andIn("nlevel", Arrays.asList(new Integer[]{1,2}));
		//jltCriteria.andEqualTo("nlevel", 1);
		jltCriteria.andEqualTo("isshow", 1);
		List<Jlt> jltList = jltService.queryListByExample(jltExample);

		//获取受害人账号
		Example shrExample = new Example(JjdShr.class);
		Example.Criteria shrCriteria = shrExample.createCriteria();
		shrCriteria.andEqualTo("jjdpk",jjdpk);
		List<JjdShr> shrList = jjdShrService.queryListByExample(shrExample);
		List<String> shrZhList = new ArrayList<>();
		//受害人所有账号信息
		if (shrList!=null && !shrList.isEmpty() && shrList.size()>0){
			for (JjdShr shr : shrList){
				if (StringUtils.isNotBlank(shr.getYhk())){
					shrZhList.add(shr.getYhk());
				}
				if (StringUtils.isNotBlank(shr.getCft())){
					shrZhList.add(shr.getCft());
				}
				if (StringUtils.isNotBlank(shr.getZfb())){
					shrZhList.add(shr.getZfb());
				}
				if (StringUtils.isNotBlank(shr.getQq())){
					shrZhList.add(shr.getQq());
					List<Map<String,String>> qqJgList = sfMxJgLstService.queryMxListByJjd(jjdpk,shr.getQq(),0);
					if (qqJgList!=null && !qqJgList.isEmpty() && qqJgList.size()>0){
						Map<String,String> qqJgMap = qqJgList.stream().filter(strMap -> StringUtils.equalsIgnoreCase(strMap.get("jdbz"),"0") && StringUtils.isNotBlank(strMap.get("fkzfzh")) && !StringUtils.equalsIgnoreCase(strMap.get("fkzfzh"),shr.getQq()) && StringUtils.indexOf(strMap.get("fkzfzh"),"tenpay.com") > 0).findFirst().orElse(null);
						if (qqJgMap!=null && !qqJgMap.isEmpty() && qqJgMap.size()>0){
							shrZhList.add(qqJgMap.get("fkzfzh"));
						}
					}
				}
				if (StringUtils.isNotBlank(shr.getWx())){
					shrZhList.add(shr.getWx());
					List<Map<String,String>> qqJgList = sfMxJgLstService.queryMxListByJjd(jjdpk,shr.getQq(),0);
					if (qqJgList!=null && !qqJgList.isEmpty() && qqJgList.size()>0){
						Map<String,String> qqJgMap = qqJgList.stream().filter(strMap -> StringUtils.equalsIgnoreCase(strMap.get("jdbz"),"0") && StringUtils.isNotBlank(strMap.get("fkzfzh")) && !StringUtils.equalsIgnoreCase(strMap.get("fkzfzh"),shr.getQq()) && StringUtils.indexOf(strMap.get("fkzfzh"),"tenpay.com") > 0).findFirst().orElse(null);
						if (qqJgMap!=null && !qqJgMap.isEmpty() && qqJgMap.size()>0){
							shrZhList.add(qqJgMap.get("fkzfzh"));
						}
					}
				}
                /*if (StringUtils.isNotBlank(shr.getJydh())){
                    Jlt thisJlt = jltList.stream().filter(jlt -> StringUtils.equalsIgnoreCase(jlt.getCardnumber(),shr.getJydh()) && jlt.getNlevel()==1 && jlt.getSertype()==3).findFirst().orElse(null);
                    String parentPk = thisJlt.getPk();
                    Jlt childJlt = jltList.stream().filter(jlt -> StringUtils.equalsIgnoreCase(jlt.getParentpk(),parentPk) && jlt.getNlevel()==2 && jlt.getSertype()==2).findFirst().orElse(null);
                    if (childJlt!=null){
                        shrZhList.add(childJlt.getCardnumber());
                    }
                }*/
			}
		}
		if (shrZhList==null || shrZhList.isEmpty() || shrZhList.size() <1){
			//throw new AppRuntimeException("受害人账号不存在，无法生成研判报告。");
		}
		//获取嫌疑人账号
        /*Example xyrExample = new Example(JjdShr.class);
        Example.Criteria xyrCriteria = xyrExample.createCriteria();
        xyrCriteria.andEqualTo("jjdpk",jjdpk);
        List<JjdXyr> xyrList = jjdXyrService.queryListByExample(xyrExample);*/

		List<Map<String,String>> mxLsList = new ArrayList<>();
		//获取嫌疑人流水(获取一级账号流水)
		List<Map<String,String>> yhkList = yhkMxJgLstService.queryMxListByJjd(jjdpk,1);
		List<Map<String,String>> sfList = sfMxJgLstService.queryMxListByJjd(jjdpk,null,1);
		if (yhkList!=null && !yhkList.isEmpty() && yhkList.size()>0)
			mxLsList.addAll(yhkList);
		if (sfList!=null && !sfList.isEmpty() && sfList.size()>0)
			mxLsList.addAll(sfList);
		if (mxLsList==null || mxLsList.isEmpty() || mxLsList.size() < 1)
			throw new AppRuntimeException("未获取到嫌疑人流水，无法生成研判报告。");
		//通过嫌疑人流水，获取受害人向嫌疑人转账记录
		List<Map<String,String>> mxList =  new ArrayList<>();
		List<Map<String,String>> mxList2 = mxLsList.parallelStream()
				.filter(strMap -> StringUtils.equalsIgnoreCase(strMap.get("jdbz"),"1")
								&& (
								(shrZhList.indexOf(strMap.get("dfzh")) >=0 && StringUtils.equalsIgnoreCase(strMap.get("ztype"),"yhk"))
										|| (StringUtils.equalsIgnoreCase(strMap.get("ztype"),"sf") &&
										(shrZhList.indexOf(strMap.get("fkzfzh")) >=0 || shrZhList.indexOf(strMap.get("fkyhzh")) >=0))
						)
				).distinct().collect(Collectors.toList());
		if (mxList2==null || mxList2.isEmpty() || mxList2.size() < 1) {
			//throw new AppRuntimeException("未获取到受害人向嫌疑人转账的记录，无法生成研判报告。");
		}else{
			//处理转账资金流向数据
			for (Map<String,String> map : mxList2){
				Map<String,String> data = new HashMap<>();
				data.put("zzsj", TimeUtil.fmtDate(TimeUtil.parseStringToDate(map.get("jysj")),"yyyy年M月d日H时m分s秒"));
				data.put("zzje",map.get("jyje"));
				if (StringUtils.equalsIgnoreCase(map.get("ztype"),"yhk")){
					data.put("zh",this.replaceAllSpecialChar(map.get("dfzh")));
					data.put("dfzh",this.replaceAllSpecialChar(map.get("zh")));
				}else if(StringUtils.equalsIgnoreCase(map.get("ztype"),"sf")){
					data.put("zh",this.replaceAllSpecialChar(map.get("fkzfzh")));
					data.put("dfzh",this.replaceAllSpecialChar(map.get("zh")));
				}
				mxList.add(data);
			}
		}
		//获取嫌疑人流水中关系为借 的MAC地址
		StringBuilder macs = new StringBuilder();
		List<Map<String,String>> macList = new ArrayList<>();
		List<Map<String,String>> macList2 = mxLsList.parallelStream()
				.filter(strMap -> StringUtils.equalsIgnoreCase(strMap.get("jdbz"),"0")
						&& StringUtils.isNotBlank(strMap.get("macdz"))
						&& !StrUtil.isContainChinese(strMap.get("macdz"))
						&& StringUtils.isNotBlank(StringUtils.trim(StringUtils.replace(StringUtils.replace(strMap.get("macdz"),"-",""),":","")))
						&& StringUtils.length(StringUtils.trim(StringUtils.replace(StringUtils.replace(strMap.get("macdz"),"-",""),":","")))==12 && !NumberUtils.isNumber(strMap.get("macdz"))
				).distinct().collect(Collectors.toList());

		if (macList2==null || macList2.isEmpty() || macList2.size() < 1){
			throw new AppRuntimeException("未获取到嫌疑人MAC，无法生成研判报告。");
		}else{
			Map<String, List<Map<String, String>>> zhMap = macList2.parallelStream().collect(Collectors.groupingBy(e -> e.get("zh")));
			if (zhMap!=null && !zhMap.isEmpty() && zhMap.size()>0){
				for (String cardnumber : zhMap.keySet()){
					//对方账号为空的跳过
					if (StringUtils.isBlank(cardnumber) || StringUtils.isBlank(cardnumber.trim()) || StringUtils.isBlank(StringUtils.replace(cardnumber.trim(),"-",""))){
						continue;
					}
					List<Map<String, String>> zhList = zhMap.get(cardnumber);
					Map<String, List<Map<String, String>>> macMap = zhList.parallelStream()
							.collect(Collectors.groupingBy(
									e -> StringUtils.trim(StringUtils.replace(StringUtils.replace(StringUtils.upperCase(e.get("macdz")),"-",""),":",""))
							));
					if (macMap!=null && !macMap.isEmpty() && macMap.size()>0){
						for (String mac : macMap.keySet()){
							List<Map<String, String>> macArray = macMap.get(mac);
							if (macArray!=null && !macArray.isEmpty() && macArray.size()>0){
								if (macs.indexOf(mac)<0){
									macs.append(StringUtils.trim(StringUtils.replace(StringUtils.replace(StringUtils.upperCase(mac),"-",""),":",""))).append(",");
								}
								Map<String, String> map = new HashMap<>();
								map.put("macdz",this.replaceAllSpecialChar(StringUtils.trim(StringUtils.replace(StringUtils.replace(StringUtils.upperCase(mac),"-",""),":",""))));
								map.put("cardnumber",cardnumber);

								Jlt jlt = jltList.parallelStream().filter(data -> StringUtils.isNotBlank(data.getAccountname()) && StringUtils.equalsIgnoreCase(data.getCardnumber(),cardnumber) && data.getNlevel()==1).findFirst().orElse(null);
								if (jlt!=null){
									map.put("xm",this.replaceAllSpecialChar(StringUtils.isNotBlank(jlt.getAccountname())?"":jlt.getAccountname()));
									map.put("sfzh",this.replaceAllSpecialChar(StringUtils.isNotBlank(jlt.getCardid())?"":jlt.getCardid()));
									map.put("phone",this.replaceAllSpecialChar(StringUtils.isNotBlank(jlt.getPhone())?"":jlt.getPhone()));
								}

								StringBuilder sb = new StringBuilder();
								for (Map<String,String> data : macArray){
									if (StringUtils.isNotBlank(data.get("ipdz"))){
										if (sb.indexOf(data.get("ipdz"))<0) {
											sb.append(data.get("ipdz")).append(data.get("ipxz")).append("、");
										}
									}
								}
								map.put("ipdz",this.replaceAllSpecialChar(sb.toString().substring(0,sb.length()-1)));
								macList.add(map);
							}
						}
					}
				}
			}
		}
		//获取一级卡MAC串并的部案件
		List<Map<String,String>> ajList = null;
		if (macs!=null && macs.length()>0){
			String[] macArray = macs.substring(0,macs.length()-1).split(",");
			ajList = gabDxzpAjxxService.queryMacCbAjxxByMacs(macArray);
		}else{
			throw new AppRuntimeException("未找到符合条件的MAC值。");
		}
		if (ajList!=null && !ajList.isEmpty() && ajList.size()>0){
			for (Map<String,String> ajMap : ajList){
				ajMap.put("fadmc",this.replaceAllSpecialChar(ajMap.get("fadmc")));
				ajMap.put("jyaq",this.replaceAllSpecialChar(ajMap.get("jyaq")));
			}
			jjd = (Jjd) codeService.translateObject(jjd,Jjd.class,"ajlb:010107");
			byte[] b = this.generatYpbg(jjd,jgz,mxList,macList,ajList);
			if (b!=null && b.length>0){
				String fileName = new StringBuilder().append("关于").append(jjd.getSldwmc()).append(jjd.getBarxm()).append("被").append(jjd.getAjlb()).append("案的研判报告.doc").toString();
				String mongoPk = this.uploadYpbg(fileName,"application/msword",b);
				logger.info("生成研判报告pk:"+mongoPk);
				JjdYpbg ypbg = new JjdYpbg();
				ypbg.setFilename(fileName);
				ypbg.setFiletype("application/msword");
				ypbg.setJjdpk(jjdpk);
				ypbg.setMongopk(mongoPk);
				this.insert(ypbg);

				flag = 1;
			}else{
				throw new AppRuntimeException("生成文件失败。");
			}
		}else{
			throw new AppRuntimeException("没有串中的案件。");
		}
		return flag;
	}

	private byte[] generatYpbg(Jjd jjd,Jgz jgz,List mxList,List macList,List ajList) throws Exception {
    	//&& mxList!=null && !mxList.isEmpty() && mxList.size()>0
		//&& macList!=null && !macList.isEmpty() && macList.size()>0 && ajList!=null && !ajList.isEmpty() && ajList.size()>0
		if (jjd!=null && jgz!=null  ) {
			Map dataMap = new HashMap();
			dataMap.put("jgmc", this.replaceAllSpecialChar(jjd.getSldwmc()));
			dataMap.put("shrxm", this.replaceAllSpecialChar(jjd.getBarxm()));
			dataMap.put("ajlx", this.replaceAllSpecialChar(jjd.getAjlb()));
			dataMap.put("ajbh", this.replaceAllSpecialChar(jjd.getJjdhm()));
			dataMap.put("jyaq", this.replaceAllSpecialChar(jjd.getJyaq()));
			dataMap.put("lrdwmc", this.replaceAllSpecialChar(jjd.getLrdwmc()));
			dataMap.put("jbrxm", this.replaceAllSpecialChar(jgz.getJbrxm()));
			dataMap.put("xcrxm", this.replaceAllSpecialChar(jgz.getXcrxm()));
			dataMap.put("jbrdh", this.replaceAllSpecialChar(jgz.getJbrdh()));
			dataMap.put("xcrdh", this.replaceAllSpecialChar(jgz.getXcrdh()));

			Date date = new Date();
			dataMap.put("scsj", TimeUtil.fmtDate(date, "yyyy年M月d日"));

			dataMap.put("mxList", mxList);
			dataMap.put("macList", macList);
			dataMap.put("ajList", ajList);
			return GeneratFileUtil.generatFile(dataMap,"/template","ypbg.ftl");
		}
		return null;
	}

	private String uploadYpbg(String fileName,String fileType,byte[] b) throws IOException {
		String mongoPk=null;
		Attachment attachment = new Attachment();
		attachment.setContent(b);
		attachment.setPk(new ObjectId().toString());
		attachment.setFilename(fileName);
		attachment.setContentType(fileType);
		attachment.setAttachmentDb("ypbg");
		attachment = attachmentService.upload(attachment);
		if (attachment!=null){
			mongoPk = attachment.getAttachmentDb()+"/"+attachment.getCatalog()+"/"+attachment.getPk();
		}
		return mongoPk;
	}

	private String replaceAllSpecialChar(String str){
    	return StringUtils.isBlank(str)?str:str.replaceAll("<","&lt;")
				.replaceAll(">","&gt;")
				.replaceAll("&","&amp;");
	}
}
